import { Component, OnInit } from '@angular/core';
import { finalize, tap } from 'rxjs/operators';
import { OutlayActionService } from 'src/app/service/actions/outlay.action-service';
import { OutlayService } from 'src/app/service/outlay.service';

@Component({
  selector: 'app-outlay',
  templateUrl: './outlay.component.html',
  styleUrls: ['./outlay.component.scss']
})
export class OutlayComponent implements OnInit {

  loading = false;
  dataList: any[] = [];
  checkIds: string[] = [];
  get checkList() {
    return this.dataList.filter(item => this.checkIds.includes(item.id));
  }
  get checkAll() {
    if (this.dataList.length <= 0) {
      return false;
    }
    return this.dataList.length === this.checkIds.length ? true : false;
  }

  get modifyDisabled(): boolean {
    return this.checkList.length !== 1 ? true : false;
  }

  get deleteDisabled(): boolean {
    return this.checkList.length !== 1 ? true : false;
  }

  get moreDisabled(): boolean {
    return this.checkList.length <= 0 ? true : false;
  }

  addCheckedId(id: string): void {
    this.checkIds.push(id);
  }
  removeCheckedId(id: string): void {
    this.checkIds = this.checkIds.filter(aId => aId !== id);
  }
  addAllIds(): void {
    this.checkIds = this.dataList.map(item => item.id);
  }

  constructor(
    private outlayService: OutlayService,
    private outlayAction: OutlayActionService,
  ) { }

  ngOnInit(): void {
    this.getList();
  }

  getList(): void {
    this.loading = true;
    this.outlayService.list().pipe(
      tap(res => {
        if (res.code === 200) {
          this.dataList = res.data;
        }
      }),
      finalize(() => {
        this.loading = false;
      })
    ).subscribe();
  }

  saveAction(): void {
    this.outlayAction.modify({
      title: 'outlay.modify.save_title',
    }).subscribe(() => {
      this.getList();
    });
  }

  updateAction(): void {
    const aData = this.checkList[0];
    this.outlayAction.modify({
      title: 'outlay.modify.modify_title',
      data: aData,
    }).subscribe(() => {
      this.getList();
      this.clearChecked();
    });
  }

  deleteAction(): void {
    const aData = this.checkList[0];
    this.outlayAction.delete(aData.id).subscribe(() => {
      this.getList();
    });
  }

  clearChecked() {
    this.checkIds = [];
  }

  onCheckAll(checked: boolean) {
    if (checked) {
      this.addAllIds();
    } else {
      this.checkIds = [];
    }
  }

  onItemCheck(id: string, checked: boolean) {
    if (checked) {
      this.addCheckedId(id);
    } else {
      this.removeCheckedId(id);
    }
  }

}
